package net.sudot.commons.security;

import net.sudot.chess.exception.BusinessException;
import net.sudot.commons.json.JsonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登陆用户拦截器
 *
 * @author tangjialin on 2017-06-14 0014.
 */
public class JwtLoginUserHandlerInterceptor extends LoginUserHandlerInterceptor {
    /** 密钥 */
    private String secret;

    public JwtLoginUserHandlerInterceptor() {
    }

    public JwtLoginUserHandlerInterceptor(Class<?> userClass, String secret, AuthenticationProvider authenticationProvider) {
        super(userClass, authenticationProvider);
        this.secret = secret;
    }

    /**
     * 请求前处理
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param handler  处理器
     * @return 是否继续执行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Jwt.Payload payload = (Jwt.Payload) request.getAttribute(Jwt.Payload.class.getSimpleName());
        if (payload == null) {
            return super.preHandle(request, response, handler);
        }
        Object loginUser = getAuthenticationProvider().getUser(payload);
        if (loginUser == null || !getUserClass().isAssignableFrom(loginUser.getClass())) {
            throw new BusinessException("用户不存在:" + JsonUtils.toJson(payload));
        }
        request.setAttribute(LoginUser.class.getSimpleName(), loginUser);
        return true;
    }

    public String getSecret() {
        return secret;
    }

    public JwtLoginUserHandlerInterceptor setSecret(String secret) {
        this.secret = secret;
        return this;
    }
}